package com.app.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.app.common.ConstantTool;
import com.app.common.Result;
import com.app.common.SystemConstant;
import com.app.model.*;
import com.app.service.*;
import com.app.utils.AliyunOSSUtils;
import com.app.utils.TokenUtils;
import com.app.vo.IdNameVo;
import com.app.vo.FileVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.List;

/**
 * 文件操作
 */
@Slf4j
@RestController
@RequestMapping("/file")
public class FileController {
    @Autowired
    private AdminUserService adminUserService;

    @Autowired
    private FileService fileService;

    @Autowired
    AliyunOSSUtils aliyunOSSUtils;
    // 管理后台查询文件
    @GetMapping("/getFileList")
    public Result getFileList(Integer page,
                              Integer limit,
                              Integer type,
                              Integer moduleId,
                              Integer businessId,
                              HttpServletRequest request) {
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String adminId = TokenUtils.verify(token);
        if (adminId.equals("false")) {
            return Result.error(405, "token已过期");
        }
        AdminUserModel adminUser = adminUserService.getById(Integer.valueOf(adminId));
        if (adminUser == null) {
            return Result.error(405, "用户不存在");
        }

        FileVo fileList = fileService.getFileList(page, limit, type,moduleId,businessId);
        return Result.success(fileList);
    }

    // 管理后台查询文件详情
    @GetMapping("/getFileById")
    public Result getFileById(Integer id, HttpServletRequest request) {
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String adminId = TokenUtils.verify(token);
        if (adminId.equals("false")) {
            return Result.error(405, "token已过期");
        }
        AdminUserModel adminUser = adminUserService.getById(Integer.valueOf(adminId));
        if (adminUser == null) {
            return Result.error(405, "用户不存在");
        }
        FileModel fileModel = fileService.getById(id);
        return Result.success(fileModel);
    }

    // 管理后台查询文件详情
    @GetMapping("/getConstant")
    public Result getConstant(Integer id, HttpServletRequest request) {
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String adminId = TokenUtils.verify(token);
        if (adminId.equals("false")) {
            return Result.error(405, "token已过期");
        }
        AdminUserModel adminUser = adminUserService.getById(Integer.valueOf(adminId));
        if (adminUser == null) {
            return Result.error(405, "用户不存在");
        }
        List<IdNameVo> fileTypeList = ConstantTool.CONSTANT_VO_LIST;
        return Result.success(fileTypeList);
    }

    // 管理后台删除文件
    @GetMapping("/delFile")
    public Result delFile(Integer id, HttpServletRequest request) {
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String adminId = TokenUtils.verify(token);
        if (adminId.equals("false")) {
            return Result.error(405, "token已过期");
        }
        AdminUserModel adminUser = adminUserService.getById(Integer.valueOf(adminId));
        if (adminUser == null) {
            return Result.error(405, "用户不存在");
        }
        FileModel fileModel = fileService.getById(id);
        try {
//            this.aliyunOSSUtils.delStorageUploadFile(fileModel.getUrl());
//            File file1 = new File(System.getProperty("user.dir")+File.separator+"file/" + fileModel.getName());
//            if (file1.delete()) {
//                System.out.println(file1.getName() + " 图片已被删除！");
//            } else {
//                System.out.println("删除图片操作失败！");
//            }
        } catch (Exception e) {
            return Result.success(e);
        }
        fileService.removeById(id);
        return Result.success("删除成功");
    }

    @GetMapping("/delFiles")
    public Result delFiles(String ids, HttpServletRequest request) {
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String adminId = TokenUtils.verify(token);
        if (adminId.equals("false")) {
            return Result.error(405, "token已过期");
        }
        AdminUserModel adminUser = adminUserService.getById(Integer.valueOf(adminId));
        if (adminUser == null) {
            return Result.error(405, "用户不存在");
        }
        if (StrUtil.isNotBlank(ids)){
            for (String id : ids.split(",")) {
                FileModel fileModel = fileService.getById(id);

                try {
//                    this.aliyunOSSUtils.delStorageUploadFile(fileModel.getUrl());
//                    File file1 = new File(System.getProperty("user.dir")+File.separator+"file/" + fileModel.getName());
//                    if (file1.delete()) {
//                        System.out.println(file1.getName() + " 图片已被删除！");
//                    } else {
//                        System.out.println("删除图片操作失败！");
//                    }
                } catch (Exception e) {
                    return Result.success(e);
                }
                fileService.removeById(id);
            }

        }
        return Result.success("删除成功");
    }


    // 管理
    @GetMapping("/recallFile")
    public Result recallFile(String filePath, HttpServletRequest request) {
        try {
            File file1 = new File(filePath);
            if (file1.delete()) {
                System.out.println(file1.getName() + " 图片已被删除！");
            } else {
                System.out.println("删除图片操作失败！");
            }
        } catch (Exception e) {
            return Result.success(e);
        }
        return Result.success("删除成功");
    }


    @Autowired
    private BannerService bannerService;

    @Autowired
    private BusinessService businessService;

    @Autowired
    private GoodsService goodsService;


    @Autowired
    private ActivityService activityService;

    @GetMapping("repairPic")
    public void repairPic(@RequestParam(value = "pic") String pic)
    {
        try{
            aliyunOSSUtils.objectStorageUploadFile(pic, FileUtil.getInputStream(System.getProperty("user.dir")+File.separator+pic));
        }catch (Exception e)
        {

        }
    }



    /**
     * 文档自动分类
     */
    @GetMapping("automaticDocumentClassification")
    public void  automaticDocumentClassification()
    {

        List<FileModel> fileModels=this.fileService.list();
        //轮播图
        List<BannerModel> bannerModelList=this.bannerService.list();
        if(CollectionUtil.isNotEmpty(bannerModelList))
        {
            for (BannerModel banner:bannerModelList
                 ) {
                fileModels.stream().forEach(s->{
                    if(s.getUrl().equals(banner.getBannerUrl()))
                    {
                        s.setModuleId(4);
                        this.fileService.updateById(s);
                    }
                });
            }
        }
        //商家信息
        List<BusinessModel> businessModelList=this.businessService.list();
        if(CollectionUtil.isNotEmpty(businessModelList))
        {
            for (BusinessModel shoper:businessModelList
            ) {
                fileModels.stream().forEach(s->{
                    if(s.getUrl().equals(shoper.getBusinessFace()))
                    {
                        s.setModuleId(1);
                        s.setBusinessId(shoper.getId());
                        this.fileService.updateById(s);
                    }
                });
            }
        }
        //积分商品
        List<GoodsModel> goodsModelList=this.goodsService.list();
        if(CollectionUtil.isNotEmpty(goodsModelList))
        {
            for (GoodsModel good:goodsModelList
            ) {
                fileModels.stream().forEach(s->{
                    if(s.getUrl().equals(good.getGoodsFace()))
                    {
                        s.setModuleId(2);
                        this.fileService.updateById(s);
                    }
                });
            }
        }

        //商家活动
        List<ActivityModel> activityModelList=this.activityService.list();
        if(CollectionUtil.isNotEmpty(activityModelList))
        {
            for (ActivityModel activityModel:activityModelList
            ) {
                fileModels.stream().forEach(s->{
                    if(s.getUrl().equals(activityModel.getCover()))
                    {
                        s.setModuleId(5);
                        s.setBusinessId(activityModel.getBusinessId());
                        this.fileService.updateById(s);
                    }
                });
            }
        }

    }

}
